package com.crh2a.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.crh2a.R
import com.crh2a.models.Lock
import kotlinx.serialization.json.Json
import kotlinx.serialization.encodeToString



class RecyclerviewAdapter(private var lockList:List<Lock>,private val wv:WebView): RecyclerView.Adapter<RecyclerviewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerviewHolder {
        var view=LayoutInflater.from(parent.context).inflate(R.layout.item_layout,parent,false)
        var holder=RecyclerviewHolder(view)
        holder.btn.setOnClickListener {
                        lockList?.let { it1 ->
                            if(it1.isNotEmpty()){
                    var lock=it1.firstOrNull{lockTemp: Lock ->
                        lockTemp.BlId==holder.tv.text.toString().toInt()
                    }
                    lock?.let {
                        val str= Json.encodeToString(it)
                        wv.evaluateJavascript("javascript:openDoor('$str')"){}
                    }

                }
            }
        }
        return holder
    }

    override fun getItemCount(): Int {
        return lockList.size
    }

    override fun onBindViewHolder(holder: RecyclerviewHolder, position: Int) {
        holder.tv.text=lockList[position].BlId.toString().padStart(3,'0')
        holder.btn.text=lockList[position].czh
    }
}
class RecyclerviewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
 var btn: Button =itemView.findViewById(R.id.btn)
    var tv: TextView =itemView.findViewById(R.id.tv)
}